<?php
/*
 ＊ 自动接收邮件
 */
include "../config/config.inc.php";
include "../config/QuickMySQL.php";

class CCrontabMail
{
    public $mail_box;
	public $lockfile;
    /* 构造函数 */
    function __construct(){
		$this->lockfile = dirname(__FILE__) . "/../lock/crontab-mail";
		$fp = fopen($this->lockfile, "w");
		if( !$fp ){
			$this->DbgPrint("打开文件{$this->lockfile}失败");
			return;
		}
		if( !flock($fp, LOCK_EX | LOCK_NB) ){
			$this->DbgPrint("锁定文件{$this->lockfile}失败");
			return;
		}
		// 接收邮件
		$this->DbgPrint("开始自动接收文件");
		try{
			$this->AutoRecvMail();
		} catch (Exception $e){
			DbgPrint($this->logfile, "自动接收邮件异常" . $e->getMessage());
		}
		$this->DbgPrint("完成自动接收文件");
		// 退出
		flock($fp, LOCK_UN);
		fclose($fp);
		unlink($this->lockfile);
    }
	/* 开始自动接收邮件 */
	function AutoRecvMail(){
		// 开始邮件读取分析
		$this->mail_box = imap_open("{server:110/pop3/notls}INBOX", "user", "pwd");
		if( false == $this->mail_box ){
			$this->DbgPrint("打开邮箱失败" . imap_last_error());
			return;
		}
		for($i = 1; $i < 10000; $i++){
			$head = imap_headerinfo($this->mail_box, $i);
			if( !$head ){
				break; // 获取邮件失败
			}
			// 读取邮件
			$body = imap_body($this->mail_box, $i);
			// 分析邮件
			if( $this->AnalyzeMail($head, $body) ){
				// 删除邮件
				imap_delete($this->mail_box, $i);
			}
		};
		// 执行删除操作
		imap_expunge($this->mail_box);
	}
	/* 分析邮件 */
	function AnalyzeMail($head, $body){
		// 验证是不是要分析的邮件
		if( !preg_match("/Undelivered Mail Returned to Sender/i", $head->subject) ){
			return false;
		}
		// 开始分析邮件
		preg_match("/<(\d{5,16}@qq.com)>/i", $body, $qma);
		preg_match("/http:\/\/service.mail.qq.com\/cgi-bin\/help\?subtype=1&&id=20022&&no=100072(\d)/i", $body, $ea);
		try{
			if( (count($qma) < 2) || (count($ea) < 2) ){
				return false;
			}
			$qqmail = $qma[1];
			$errcode = $ea[1];
			// 执行语句
			if(2 == $errcode){
				// 该服务器IP的发信频率超过QQ邮箱限制。
				$sql = "insert into t_email_failed(sm_to, sm_flag) values('{$qqmail}', 2)";
			} else if(8 == $errcode){
				// 您要发送的收件人不存在。
				$sql = "insert into t_email_failed(sm_to, sm_flag) values('{$qqmail}', 8)";
			} else if(6 == $errcode){
				// 该邮件内容涉嫌大量群发，并且被多数用户投诉为垃圾邮件。
				$sql = "insert into t_email_failed(sm_to, sm_flag) values('{$qqmail}', 6)";
			}else {
				return false;
			}
			// 执行SQL语句
			return QuickMySQL::quickExecute($sql);
		} catch (Exception $e) {
			return false;
		}
	}
	/* 打印日志 */
	function DbgPrint($log){
		$path = dirname(__FILE__);
		$fp = fopen("{$path}/../log/crontab-mail.log", "a");
		if( !$fp )
			return;
		fputs($fp, date("[Y-m-d H:i:s]\t"));
		fputs($fp, preg_replace("/[\r\n]/i", " ", $log) . "\r\n");
		fclose($fp);
	}
	
};

$cc = new CCrontabMail();
?>